package com.bwda.dsrs.base.util;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;

/**
 * AES加密
 *
 * @author yanyuemei
 * @date 2019-05-06
 */
public class AesEncryptPaddingUtil {
    /**
     * Logger for this class
     */
    private static Logger logger = LoggerFactory.getLogger(AesEncryptPaddingUtil.class);

    public static final String IV = "face0123456789ai";

    private static final int KEY_LENGTH=16;

    /**
     * AES加密算法
     * 加密用的Key 可以用26个字母和数字组成，最好不要用保留字符，虽然不会错，至于怎么裁决，个人看情况而定    此处使用AES-128-CBC加密模式，key需要为16位。
     * @param sSrc
     * @param sKey
     * @return
     * */
    public static String encrypt(String sSrc, String sKey) throws Exception {

        if (sKey == null) {
            System.out.print("Key为空null");
            return null;
        }
        // 判断Key是否为16位
        if (sKey.length() != KEY_LENGTH) {
            System.out.print("Key长度不是16位");
            return null;
        }
        // 根据指定的编码查找Charset
        Charset charset = Charset.forName("utf-8");
        byte[] raw = sKey.getBytes(charset);

        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        //"算法/模式/补码方式"
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        //使用CBC模式，需要一个向量iv，可增加加密算法的强度
        IvParameterSpec iv = new IvParameterSpec(IV.getBytes(charset));
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes(charset));
        //此处使用BAES64做转码功能，同时能起到2次
        return Base64.encodeBase64String(encrypted);
    }

    /**
     * 解密
     * @param sSrc
     * @param sKey
     * @return
     * @throws Exception
     */
    public static String decrypt(String sSrc, String sKey) throws Exception {

        // 判断Key是否正确
        if (sKey == null) {
            System.out.print("Key为空null");
            return null;
        }
        // 判断Key是否为16位
        if (sKey.length() != KEY_LENGTH) {
            System.out.print("Key长度不是16位");
            return null;
        }
        Charset charset = Charset.forName("ASCII");
        byte[] raw = sKey.getBytes(charset);

        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec iv = new IvParameterSpec(IV.getBytes(charset));
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
        //先用bAES64解密
        byte[] encrypted1 = Base64.decodeBase64(sSrc);
        try {
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original,"UTF-8");
            return originalString;
        } catch (Exception e) {
            logger.info(e.toString());
            return null;
        }
    }

    public static void main(String[] args) throws Exception {

        String pwd = "123456";
        String epwd = encrypt(pwd, "dvyYRQlnPRCMdQSe");
        System.out.println("加密后："+epwd);
        System.out.println("解密后："+decrypt("gOxkz2NRSZpKzClsKGkrGQ==", "dvyYRQlnPRCMdQSe"));

        //System.out.println(Decrypt("NQuUxwll4qL22YpZi2Lu1A==", "dvyYRQlnPRCMdQSe"));
    }
}
